import time
import os
import platform

import bs4

import win32gui
import win32api
import win32con
import win32clipboard
import pyperclip

from selenium import webdriver

from worker import worker, dd ,dm , lock_wrapper
from exceptions import *

class msyh(worker):
    """
    docstring for msyh
    """
    def __init__(self, backend:"后台根地址",lock:"锁",config_entity):
        super(msyh, self).__init__(backend,lock,config_entity,old_title = "IEFrame")
        if platform.win32_ver()[0] == '10':
            self.base_picture_path = "msyh/image_win10/"
        else:
            self.base_picture_path = "msyh/image_win7/"
        self.risk = float(config_entity['risk'])
        
        self.login_url = 'https://nper.cmbc.com.cn/pweb/static/login.html'
        self.working_url = 'https://nper.cmbc.com.cn/pweb/static/main.html'
        self.check_url = 'https://nper.cmbc.com.cn/pweb/GetOpenBankByCardBin.do'

        self.dd_key_map={'j': 407, '1': 201, '2': 202, 's': 402, '4': 204, "'": 411, '6': 206, 'w': 302, '8': 208, '0': 210 , '9': 209, ']': 312, 'u': 307, '.': 509, 'd': 403, 'r': 304, 'SHIFT': 500, 'e': 303, '5': 205, 'y': 306, 'x': 502, '7': 207, 'f': 404, 'b': 505, 'h': 406, 'c': 503, '/': 510, 't': 305, ',': 508, 'z': 501, 'l': 409, '[': 311, 'v': 504, 'p': 310, 'n': 506, '3': 203, 'a': 401, 'o': 309, 'g': 405, ';': 410, 'k': 408, 'q': 301, '\\': 313, 'm': 507, 'i': 308}
        print("启动ie中")
        self.ie = webdriver.Ie()
        self.ie.get(self.login_url)
        self.getHwnd(True)
        print(config_entity['mankind_login'])
        print(dd.SetSimMode(1))
        if config_entity['mankind_login'] != '0':   
            print("IE启动成功,你有30秒的时间输入网银密码并登录")
            time.sleep(30) 
        else:
            self.login()
        time.sleep(5)

        self.session.cookies.update({i['name']:i['value'] for i in self.ie.get_cookies()})

        dm.SetWindowText(self.hwnd,"hook by ck")

    @lock_wrapper
    def key_single_with_dd(self,char):
        win32gui.SetForegroundWindow(self.hwnd)
        dd.KeyPressChar(char)
        time.sleep(0.3)
        # dd.DD_key(self.dd_key_map[char],1)
        # time.sleep(0.3)
        # dd.DD_key(self.dd_key_map[char],2)


    @lock_wrapper  
    def key_word_with_dd(self,word,delay=0.3):
        for char in word:
            self.key_single_with_dd(char)
            time.sleep(delay)

    def goto_zz(self):
        if not self.wait_unit_findpic_or_timeout("other_bank.bmp"):
            raise ToZZException("登录完成跳转时网络异常")
        else:
            self.findPicture_relative_and_click("other_bank.bmp",40,7)

    def fill_bank_info(self,name,account,money):
        print("开始填写转账信息")
        if self.wait_unit_findpic_or_timeout("other_bank.bmp",sim=1,timeout=3) and not self.wait_unit_findpic_or_timeout("same_bank.bmp",sim=1,timeout=3):
            raise LockedException(self.wid,"进入跨行转账页面失败")
        if self.is_msyh_account(account):
            time.sleep(2)
            self.findPicture_relative_and_click("same_bank.bmp",40,7)
            if not self.wait_unit_findpic_or_timeout("other_bank.bmp",sim=1,timeout=3) and self.wait_unit_findpic_or_timeout("same_bank.bmp",sim=1,timeout=3):
                raise LockedException(self.wid,"进入本行转账页面失败")

        self.web_find_and_send_key("input[v-model=\"Amount\"]",money,LockedException(self.wid,"输入金额,input not found"))
        self.web_find_and_send_key("input[v-model=\"PayeeAcName\"]",name,LockedException(self.wid,"输入姓名,input not found"))
        self.web_find_and_send_key("input[v-model=\"PayeeAcNo\"]",account,LockedException(self.wid,"输入银行账号,input not found"))

        time.sleep(1)
        if self.wait_unit_findpic_or_timeout("other_bank.bmp"):
            self.findPicture_relative_and_click("other_bank.bmp")
            time.sleep(2)

        self.web_find_and_click("input[value=\"下一步\"]",LockedException(self.wid,"填写信息后，‘下一步’ not found"))

        time.sleep(1)
        print("填写信息完成")

    def pay(self):
        # if not self.findPicture_relative_and_click("next.bmp",sim=1):
        #     raise BeforePayException(self.wid,"付款前点击 下一步 失败")
        print("going to pay")
        if not self.wait_unit_findpic_or_timeout("pay_password.bmp"):
            jsonError = self.ie.find_element_by_id('jsonError')
            if jsonError.text == '':
                try:
                    over30w = self.ie.find_elements_by_css_selector("input[value=\"继续\"]")
                    print(over30w)
                    if len(over30w) != 0:
                        over30w[0].click()
                        time.sleep(1)
                        return self.pay()
                    elif self.ie.find_element_by_id("shouquanPwd").text == '交易密码':
                        pass
                except Exception as e:
                    raise 
            else:
                raise InPayException(self.wid,jsonError.text)

        time.sleep(0.5)
        self.key_word_with_dd(self.pay_password)
        time.sleep(0.5)

        self.web_find_and_click("input[value=\"提交\"]",InPayException(self.wid,"付款密码输入后,未能找到提交按钮"))

        if self.wait_unit_findpic_or_timeout("u.bmp"):
            flag,x,y = self.findPicture_relative("u.bmp",delay=1)
            print("输入U宝密码")
            self.key_word_with_dd(self.login_password)
            print("输入完毕")
            time.sleep(5)
            if self.findPicture_relative_and_click("u_submit.bmp"):
                return self.checkPayInfo()
            else:
                if not self.checkPayInfoInLog():
                    raise InPayException(self.wid,"输入U宝密码后,出现异常")
                else:
                    print("输入U宝密码超时,但查询历史发现已转账成功")
                    return True
        else:
            print("not found")


    def getHwnd(self,call=False):
        if not call:
            return
        self.hwnd = win32gui.FindWindow("IEFrame",None)
        if self.hwnd == 0:
            raise GetMonitorHwndException("浏览器打开失败") 

    def login(self):
        print("尝试登录")
        print(self.ie.current_url)
        if not self.wait_unit_findpic_or_timeout("loading.bmp",sim=0.9,timeout=30):
            raise LoginException("网银安全控件加载失败 或 U盾未插入")
        time.sleep(2)
        flag,x,y = self.findPicture_relative("loading.bmp",sim=0.9)
        if not flag:
            raise LoginException("登录密码位置被遮挡了吗？")
        self.left_click(x,y,-100,80)
        time.sleep(0.3)
        self.left_click(x,y,-100,80)
        time.sleep(1)
        self.key_word_with_dd(self.login_password)
        time.sleep(3.5)
        #self.findPicture_relative_and_click("login.bmp")
        self.ie.find_element_by_id("loginButton").click()
        time.sleep(5)
        if self.ie.current_url != self.working_url:
            print(self.ie.current_url)
            raise LoginException("登录后出现网络异常？！")
        print("登录成功")

    def checkPayInfo(self):
        if self.wait_unit_findpic_or_timeout("success.bmp",timeout=40):
            objs = self.ie.find_elements_by_class_name("oktishi")
            text = ''
            for i in objs:
                text += i.text
            print(text)
            return True
        elif self.findPicture_relative_onlybool("error_alert.bmp"):
            objs = self.ie.find_elements_by_class_name("oktishi")
            text = ''
            for i in objs:
                text += i.text
            print(text)
            raise BankInfoErrorException(self.wid,text)
            #return False,text
        else:
            jsonError = self.ie.find_element_by_id('jsonError')
            raise AfterPayException(self.wid,jsonError.text)

    def checkPayInfoInLog(self):
        self.back()
        try:
            time.sleep(4)
            self.ie.find_elements_by_link_text("查询明细")[0].click()
            time.sleep(2)
            table = self.ie.find_element_by_id("DataTable")
            trs = table.find_elements_by_tag_name("tr")
            trs.pop(0)
            for i in trs:
                t = i.text.split(" ")
                bank_account = "".join(t[9:])
                bank_name = t[8]
                money = t[5]
                _type = t[3]
                if _type != "转出":
                    continue
                if money != self.money or bank_name != self.bank_name or bank_account != self.bank_account:
                    continue
                else:
                    self.back()
                    return True
        except Exception as e:
            raise e
        self.back()
        return False
            
    def back(self):
        self.ie.refresh()

    def is_msyh_account(self,account):
        tmp = self.session.post(self.check_url,json={'CardBin':account}).json()
        print(tmp)
        if tmp['IBPSBank'] != '305100000013':
            self.same_bank = False
            return False
        else:
            self.same_bank = True
            return True

    def web_find_and_send_key(self, css_selector, value, exc = None):
        time.sleep(1)
        tmp = self.ie.find_elements_by_css_selector(css_selector)
        if len(tmp) != 0:
            tmp[0].send_keys(value)
        else:
            raise exc

    def web_find_and_click(self, css_selector, exc = None):
        time.sleep(1)
        tmp = self.ie.find_elements_by_css_selector(css_selector)
        if len(tmp) != 0:
            tmp[0].click()
        else:
            raise exc
